package com.cms.controller.front;

import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.cms.domain.Feedback;
import com.cms.entity.Div;
import com.cms.entity.DivField;
import com.cms.service.DivFieldService;
import com.cms.service.DivService;
import com.cms.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Controller - 自定义
 *
 *
 *
 */
@Slf4j
@Controller("frontDivController")
@RequestMapping("/div")
public class DivController extends BaseController {

    @Autowired
    private DivService divService;

    @Autowired
    private DivFieldService divFieldService;

    /**
     * 保存
     */
    @ResponseBody
    @RequestMapping("/save")
    public Feedback save(Integer id){
        log.info("保存自定义div操作...");
        Div div = divService.getById(id);
        List<DivField> divFields = divFieldService.findList(id);
        List<String> columnNames = new ArrayList<>();
        List<String> columnValues = new ArrayList<>();
        for(DivField divField : divFields){
            String value = WebUtils.getRequest().getParameter(divField.getName());
            columnNames.add(divField.getName());
            columnValues.add(value);
        }
        columnNames.add("createDate");
        columnNames.add("updateDate");
        columnValues.add(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        columnValues.add(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        SqlRunner.db().insert("insert into "+div.getTableName()+"(`"+ StringUtils.join(columnNames,"`,`")+"`) values('"+StringUtils.join(columnValues,"','")+"')");
        return Feedback.success(new HashMap<>());
    }
}
